<!DOCTYPE html>
<html>
<head>
    <title>专家数据导入管理</title>
    <#include "../../include/head-file.ftl"/>
    <link rel="stylesheet" href="${base}/static/ms-admin/4.7.2/css/index.css">
    <style>
        .ms-admin-import-container {
            height: calc(100vh - 60px);
        }
        
        .ms-container {
            height: calc(100% - 50px);
            padding: 0;
            overflow-y: auto;
            background: transparent;
        }
        
        .ms-header {
            padding: 0 20px;
            margin-bottom: 10px;
            background-color: #fff;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 1px 4px rgba(0,0,0,.08);
        }
        
        .ms-header-left {
            display: flex;
            align-items: center;
        }
        
        .ms-header-title {
            font-size: 20px;
            font-weight: 600;
            color: #303133;
            margin: 0;
            position: relative;
            padding-left: 16px;
            letter-spacing: 0.5px;
            display: flex;
            align-items: center;
        }
        
        .ms-header-title:before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 22px;
            background: linear-gradient(to bottom, #409EFF, #67c23a);
            border-radius: 2px;
        }
        
        .ms-header-subtitle {
            color: #909399;
            font-size: 14px;
            font-weight: normal;
            margin-left: 15px;
            font-style: italic;
            opacity: 0.9;
        }
        
        .content-wrapper {
            padding: 20px;
            background-color: #fff;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        
        .section-title {
            position: relative;
            padding-left: 12px;
            font-size: 16px;
            font-weight: 500;
            color: #333;
            margin-bottom: 15px;
            border-left: 3px solid #409EFF;
            display: flex;
            align-items: center;
        }
        
        .section-icon {
            margin-right: 6px;
            color: #409EFF;
            font-size: 18px;
        }
        
        .upload-area {
            border: 2px dashed #dcdfe6;
            border-radius: 6px;
            text-align: center;
            padding: 30px 20px;
            cursor: pointer;
            margin-bottom: 20px;
            transition: all 0.3s;
        }
        
        .upload-area:hover {
            border-color: #409EFF;
            background-color: rgba(64, 158, 255, 0.05);
        }
        
        .upload-icon {
            font-size: 48px;
            color: #c0c4cc;
            margin-bottom: 10px;
        }
        
        .upload-text {
            font-size: 14px;
            color: #606266;
            margin-bottom: 10px;
        }
        
        .step-area {
            margin-top: 30px;
        }
        
        .template-area {
            margin: 20px 0;
            padding: 15px;
            background-color: #f5f7fa;
            border-radius: 4px;
            transition: all 0.3s ease;
        }
        
        .template-area:hover {
            background-color: #ecf5ff;
        }
        
        .template-btn {
            margin-right: 10px;
            margin-bottom: 8px;
        }
        
        .result-area {
            margin-top: 20px;
        }
        
        .data-preview {
            margin-top: 20px;
            max-height: 300px;
            overflow-y: auto;
            border-radius: 4px;
            border: 1px solid #ebeef5;
        }
        
        .import-result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 4px;
            animation: fadeIn 0.5s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .import-success {
            background-color: #f0f9eb;
            color: #67c23a;
            border-left: 4px solid #67c23a;
        }
        
        .import-error {
            background-color: #fef0f0;
            color: #f56c6c;
            border-left: 4px solid #f56c6c;
        }
        
        .tab-content {
            margin-top: 20px;
        }
        
        .tips-area {
            margin: 20px 0;
            padding: 15px;
            background-color: #fdf6ec;
            border-radius: 4px;
            color: #e6a23c;
            border-left: 4px solid #e6a23c;
        }
        
        .el-step.is-success .el-step__title,
        .el-step.is-success .el-step__description {
            color: #67c23a !important;
        }
        
        .el-step.is-process .el-step__title,
        .el-step.is-process .el-step__description {
            color: #409EFF !important;
        }
        
        .step-content-enter-active, .step-content-leave-active {
            transition: all 0.3s;
        }
        
        .step-content-enter, .step-content-leave-to {
            opacity: 0;
            transform: translateY(10px);
        }
        
        [v-cloak] {
            display: none;
        }
    </style>
</head>
<body>
<div id="app" class="ms-admin-import-container" v-cloak>
    <el-container>
        <el-header class="ms-header" height="50px">
            <div class="ms-header-left">
                <h1 class="ms-header-title">
                    <i class="el-icon-upload2" style="margin-right: 8px; font-size: 22px;"></i>
                    专家数据导入
                </h1>
                <span class="ms-header-subtitle">批量导入专家、项目及企业数据</span>
            </div>
            <div>
                <el-button class="return-button" @click="returnToIndex">返回</el-button>
            </div>
        </el-header>
        <el-main class="ms-container">
            <div class="content-wrapper">
                <div class="section-title">
                    <i class="el-icon-upload section-icon"></i>数据导入流程
                </div>
                
                <el-steps :active="activeStep" finish-status="success" align-center>
                    <el-step title="下载模板" description="获取导入模板"></el-step>
                    <el-step title="上传数据" description="上传填写好的表格"></el-step>
                    <el-step title="数据预览" description="检查导入数据"></el-step>
                    <el-step title="确认导入" description="完成数据导入"></el-step>
                </el-steps>
                
                <transition name="step-content">
                    <div class="step-area">
                        <!-- 步骤1：下载模板 -->
                        <div v-if="activeStep === 0" class="template-area">
                            <h4><i class="el-icon-document section-icon"></i>请下载对应的数据模板，按照模板格式填写数据</h4>
                            <div style="margin-top: 15px;">
                                <el-button type="primary" class="template-btn" @click="downloadTemplate('expert')">
                                    <i class="el-icon-download"></i> 专家信息模板
                                </el-button>
                                <el-button type="primary" class="template-btn" @click="downloadTemplate('project')">
                                    <i class="el-icon-download"></i> 项目信息模板
                                </el-button>
                                <el-button type="primary" class="template-btn" @click="downloadTemplate('company')">
                                    <i class="el-icon-download"></i> 企业信息模板
                                </el-button>
                            </div>
                            <div class="tips-area">
                                <p><i class="el-icon-warning-outline"></i> 注意事项：</p>
                                <ul>
                                    <li>请严格按照模板格式填写数据，不要修改模板结构</li>
                                    <li>请确保必填字段不为空，特别是编号字段（作为主键）</li>
                                    <li>多值字段请使用英文逗号分隔，如"ZJ-001, ZJ-002"</li>
                                </ul>
                            </div>
                            <div style="margin-top: 20px; text-align: right;">
                                <el-button class="next-button" type="primary" @click="nextStep">下一步</el-button>
                            </div>
                        </div>
                        
                        <!-- 步骤2：上传数据 -->
                        <div v-if="activeStep === 1">
                            <div class="upload-area" @click="triggerUpload">
                                <input type="file" ref="fileInput" style="display: none" @change="handleFileChange" accept=".xlsx,.xls" />
                                <i class="el-icon-upload upload-icon"></i>
                                <div class="upload-text">点击或拖拽文件到此区域上传</div>
                                <div class="el-upload__tip">只支持 Excel 文件 (.xlsx, .xls)</div>
                            </div>
                            
                            <el-tabs v-model="activeTab" type="card">
                                <el-tab-pane label="专家信息" name="expert">
                                    <div class="upload-info" v-if="uploadStatus.expert">
                                        <el-tag type="success" v-if="uploadStatus.expert.status === 'success'">
                                            <i class="el-icon-check"></i> 文件已上传：{{ uploadStatus.expert.filename }}
                                        </el-tag>
                                        <el-tag type="danger" v-else-if="uploadStatus.expert.status === 'error'">
                                            <i class="el-icon-close"></i> 上传失败：{{ uploadStatus.expert.message }}
                                        </el-tag>
                                    </div>
                                </el-tab-pane>
                                <el-tab-pane label="项目信息" name="project">
                                    <div class="upload-info" v-if="uploadStatus.project">
                                        <el-tag type="success" v-if="uploadStatus.project.status === 'success'">
                                            <i class="el-icon-check"></i> 文件已上传：{{ uploadStatus.project.filename }}
                                        </el-tag>
                                        <el-tag type="danger" v-else-if="uploadStatus.project.status === 'error'">
                                            <i class="el-icon-close"></i> 上传失败：{{ uploadStatus.project.message }}
                                        </el-tag>
                                    </div>
                                </el-tab-pane>
                                <el-tab-pane label="企业信息" name="company">
                                    <div class="upload-info" v-if="uploadStatus.company">
                                        <el-tag type="success" v-if="uploadStatus.company.status === 'success'">
                                            <i class="el-icon-check"></i> 文件已上传：{{ uploadStatus.company.filename }}
                                        </el-tag>
                                        <el-tag type="danger" v-else-if="uploadStatus.company.status === 'error'">
                                            <i class="el-icon-close"></i> 上传失败：{{ uploadStatus.company.message }}
                                        </el-tag>
                                    </div>
                                </el-tab-pane>
                            </el-tabs>
                            
                            <div style="margin-top: 20px; text-align: right;">
                                <el-button @click="activeStep--">上一步</el-button>
                                <el-button type="primary" @click="validateAndPreview" :disabled="!hasUploadedFiles">下一步</el-button>
                            </div>
                        </div>
                        
                        <!-- 步骤3：数据预览 -->
                        <div v-if="activeStep === 2">
                            <div class="validation-summary" style="margin-top: 20px;">
                                <el-alert
                                    :title="validationSummary.title"
                                    :type="validationSummary.type"
                                    :description="validationSummary.description"
                                    show-icon>
                                </el-alert>
                            </div>
                            
                            <div style="margin-top: 20px; text-align: right;">
                                <el-button @click="activeStep--">上一步</el-button>
                                <el-button type="primary" @click="nextStep" :disabled="!isDataValid">下一步</el-button>
                            </div>
                        </div>
                        
                        <!-- 步骤4：确认导入 -->
                        <div v-if="activeStep === 3">
                            <div class="import-confirm">
                                <el-alert
                                    title="确认导入"
                                    type="warning"
                                    description="导入数据将覆盖同编号的原有数据，确认是否继续进行导入操作？"
                                    show-icon>
                                </el-alert>
                                
                                <div style="margin-top: 20px;">
                                    <h4><i class="el-icon-info-filled section-icon"></i>导入摘要：</h4>
                                    <el-card shadow="hover" style="margin-top: 10px;">
                                        <el-descriptions border direction="vertical">
                                            <el-descriptions-item label="专家信息">
                                                <el-tag size="medium">{{ importSummary.expert.total }}</el-tag> 条，有效 
                                                <el-tag size="medium" type="success">{{ importSummary.expert.valid }}</el-tag> 条
                                            </el-descriptions-item>
                                            <el-descriptions-item label="项目信息">
                                                <el-tag size="medium">{{ importSummary.project.total }}</el-tag> 条，有效 
                                                <el-tag size="medium" type="success">{{ importSummary.project.valid }}</el-tag> 条
                                            </el-descriptions-item>
                                            <el-descriptions-item label="企业信息">
                                                <el-tag size="medium">{{ importSummary.company.total }}</el-tag> 条，有效 
                                                <el-tag size="medium" type="success">{{ importSummary.company.valid }}</el-tag> 条
                                            </el-descriptions-item>
                                        </el-descriptions>
                                    </el-card>
                                </div>
                            </div>
                            
                            <div style="margin-top: 20px; text-align: right;">
                                <el-button @click="activeStep--">上一步</el-button>
                                <el-button type="primary" @click="importData" :loading="importing" :disabled="importing">{{ importing ? '导入中...' : '确认导入' }}</el-button>
                            </div>
                        </div>
                        
                        <!-- 导入结果 - 仅在出错时显示 -->
                        <div v-if="importResult.show && !importResult.success" class="import-result import-error">
                            <h4>
                                <i class="el-icon-error"></i>
                                {{ importResult.message }}
                            </h4>
                            <div v-if="importResult.details">
                                <p>导入详情：</p>
                                <ul>
                                    <li v-for="(item, index) in importResult.details" :key="index">{{ item }}</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </transition>
            </div>
        </el-main>
    </el-container>
</div>

<script>
    var app = new _Vue({
        el: '#app',
        data: function() {
            return {
                activeStep: 0,              // 当前步骤
                activeTab: 'expert',        // 当前上传选项卡
                previewTab: 'expert',       // 当前预览选项卡
                
                // 上传状态
                uploadStatus: {
                    expert: null,
                    project: null,
                    company: null
                },
                
                // 预览数据
                previewData: {
                    expert: [],
                    project: [],
                    company: []
                },
                
                // 验证汇总
                validationSummary: {
                    title: '',
                    type: 'info',
                    description: ''
                },
                
                // 导入汇总
                importSummary: {
                    expert: { total: 0, valid: 0 },
                    project: { total: 0, valid: 0 },
                    company: { total: 0, valid: 0 }
                },
                
                // 导入结果
                importResult: {
                    show: false,
                    success: false,
                    message: '',
                    details: []
                },
                
                importing: false    // 是否正在导入
            };
        },
        computed: {
            // 是否已上传文件
            hasUploadedFiles: function() {
                return (this.uploadStatus.expert && this.uploadStatus.expert.status === 'success') ||
                       (this.uploadStatus.project && this.uploadStatus.project.status === 'success') ||
                       (this.uploadStatus.company && this.uploadStatus.company.status === 'success');
            },
            
            // 数据是否有效
            isDataValid: function() {
                const expertValid = this.previewData.expert.length === 0 || 
                                  this.previewData.expert.every(item => item._valid);
                const projectValid = this.previewData.project.length === 0 || 
                                   this.previewData.project.every(item => item._valid);
                const companyValid = this.previewData.company.length === 0 || 
                                   this.previewData.company.every(item => item._valid);
                
                return expertValid && projectValid && companyValid;
            }
        },
        methods: {
            // 返回首页
            returnToIndex: function() {
                location.href = ms.manager + "/expertmanage/relation/index";
            },
            
            // 下一步
            nextStep: function() {
                this.activeStep++;
            },
            
            // 下载模板
            downloadTemplate: function(type) {
                let templateUrl = ms.manager + "/expertmanage/relation/importTemplate/" + type;
                window.open(templateUrl, '_blank');
            },
            
            // 触发文件上传
            triggerUpload: function() {
                this.$refs.fileInput.click();
            },
            
            // 处理文件变化
            handleFileChange: function(event) {
                const file = event.target.files[0];
                if (!file) return;
                
                // 检查文件类型
                if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
                    this.$message.error('只支持Excel文件（.xlsx, .xls）');
                    return;
                }
                
                // 上传文件
                this.uploadFile(file, this.activeTab);
                
                // 清除文件输入，允许选择相同文件
                this.$refs.fileInput.value = '';
            },
            
            // 上传文件
            uploadFile: function(file, type) {
                const formData = new FormData();
                formData.append('file', file);
                formData.append('type', type);
                
                // 设置上传状态
                this.uploadStatus[type] = {
                    status: 'uploading',
                    filename: file.name
                };
                
                // 发送请求
                const url = ms.manager + "/expertmanage/relation/uploadExcel";
                axios.post(url, formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }).then(response => {
                    const res = response.data;
                    if (res.result) {
                        this.uploadStatus[type] = {
                            status: 'success',
                            filename: file.name,
                            data: res.data
                        };
                        this.$message.success('文件上传成功');
                    } else {
                        this.uploadStatus[type] = {
                            status: 'error',
                            filename: file.name,
                            message: res.msg || '上传失败'
                        };
                        this.$message.error(res.msg || '上传失败');
                    }
                }).catch(error => {
                    this.uploadStatus[type] = {
                        status: 'error',
                        filename: file.name,
                        message: '系统错误，请重试'
                    };
                    this.$message.error('上传失败：' + (error.message || '系统错误'));
                });
            },
            
            // 验证并预览数据
            validateAndPreview: function() {
                // 检查是否有上传的文件
                if (!this.hasUploadedFiles) {
                    this.$message.warning('请先上传至少一个Excel文件');
                    return;
                }
                
                // 显示加载提示
                const loading = this.$loading({
                    lock: true,
                    text: '正在验证数据...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                
                // 获取验证数据
                const url = ms.manager + "/expertmanage/relation/previewExcel";
                axios.get(url).then(response => {
                    const res = response.data;
                    loading.close();
                    
                    if (res.result) {
                        // 设置预览数据 (用于计数和验证)
                        this.previewData = res.data.preview || {
                            expert: [],
                            project: [],
                            company: []
                        };
                        
                        // 确保所有类型的预览数据都有默认值
                        if (!this.previewData.expert) this.previewData.expert = [];
                        if (!this.previewData.project) this.previewData.project = [];
                        if (!this.previewData.company) this.previewData.company = [];
                        
                        // 设置导入汇总
                        this.importSummary = {
                            expert: {
                                total: this.previewData.expert.length,
                                valid: this.previewData.expert.filter(item => item._valid).length
                            },
                            project: {
                                total: this.previewData.project.length,
                                valid: this.previewData.project.filter(item => item._valid).length
                            },
                            company: {
                                total: this.previewData.company.length,
                                valid: this.previewData.company.filter(item => item._valid).length
                            }
                        };
                        
                        // 设置验证汇总
                        this.updateValidationSummary();
                        
                        // 进入下一步
                        this.nextStep();
                        
                        // 如果没有任何数据，提示用户
                        if (this.previewData.expert.length === 0 && 
                            this.previewData.project.length === 0 && 
                            this.previewData.company.length === 0) {
                            this.$message.warning('没有找到有效数据，请检查上传的文件');
                        }
                    } else {
                        this.$message.error(res.msg || '数据验证失败');
                    }
                }).catch(error => {
                    loading.close();
                    this.$message.error('系统错误：' + (error.message || '未知错误'));
                });
            },
            
            // 更新验证汇总
            updateValidationSummary: function() {
                // 确保预览数据存在且有效
                if (!this.previewData) {
                    this.previewData = { expert: [], project: [], company: [] };
                }
                
                // 计算各类数据的有效数量
                const expertTotal = this.previewData.expert ? this.previewData.expert.length : 0;
                const expertValid = this.previewData.expert ? this.previewData.expert.filter(item => item._valid).length : 0;
                
                const projectTotal = this.previewData.project ? this.previewData.project.length : 0;
                const projectValid = this.previewData.project ? this.previewData.project.filter(item => item._valid).length : 0;
                
                const companyTotal = this.previewData.company ? this.previewData.company.length : 0;
                const companyValid = this.previewData.company ? this.previewData.company.filter(item => item._valid).length : 0;
                
                // 检查是否所有数据都有效
                const allValid = expertValid === expertTotal && 
                                projectValid === projectTotal && 
                                companyValid === companyTotal;
                
                // 总数据量
                const totalRecords = expertTotal + projectTotal + companyTotal;
                const validRecords = expertValid + projectValid + companyValid;
                
                console.log("验证汇总:", {
                    expertTotal, expertValid,
                    projectTotal, projectValid,
                    companyTotal, companyValid
                });
                
                // 根据验证结果设置摘要信息
                if (totalRecords === 0) {
                    this.validationSummary = {
                        title: '没有找到数据',
                        type: 'warning',
                        description: '没有可导入的数据，请检查上传的文件'
                    };
                } else if (allValid) {
                    this.validationSummary = {
                        title: '全部数据验证通过',
                        type: 'success',
                        description: '专家信息: ' + expertValid + '/' + expertTotal + ' 条有效, 项目信息: ' + projectValid + '/' + projectTotal + ' 条有效, 企业信息: ' + companyValid + '/' + companyTotal + ' 条有效'
                    };
                } else {
                    this.validationSummary = {
                        title: '存在无效数据',
                        type: 'warning',
                        description: '专家信息: ' + expertValid + '/' + expertTotal + ' 条有效, 项目信息: ' + projectValid + '/' + projectTotal + ' 条有效, 企业信息: ' + companyValid + '/' + companyTotal + ' 条有效, 请检查无效数据后继续'
                    };
                }
            },
            
            // 导入数据
            importData: function() {
                // 显示确认对话框
                this.$confirm('导入数据将覆盖同编号的原有数据，确认继续吗？', '确认导入', {
                    confirmButtonText: '确认导入',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 用户确认，执行导入
                    this.doImportData();
                }).catch(() => {
                    // 用户取消操作
                    this.$message({
                        type: 'info',
                        message: '已取消导入操作'
                    });
                });
            },
            
            // 执行实际的导入操作
            doImportData: function() {
                this.importing = true;
                
                // 发送导入请求
                const url = ms.manager + "/expertmanage/relation/importExcel";
                axios.post(url).then(response => {
                    const res = response.data;
                    this.importing = false;
                    
                    if (res.result) {
                        // 设置导入结果(不再显示)
                        this.importResult = {
                            show: false,
                            success: true,
                            message: '数据导入成功',
                            details: res.data.details || []
                        };
                        
                        // 显示成功消息弹窗
                        this.$notify({
                            title: '导入成功',
                            message: '数据导入成功，共导入：' + 
                                    (res.data.details ? res.data.details.join('，') : ''),
                            type: 'success',
                            duration: 5000,
                            position: 'top-right'
                        });
                        
                        // 自动返回到首页
                        setTimeout(() => {
                            location.href = ms.manager + "/expertmanage/relation/index";
                        }, 3000);
                    } else {
                        this.importResult = {
                            show: true,
                            success: false,
                            message: res.msg || '数据导入失败',
                            details: res.data ? res.data.details : null
                        };
                    }
                }).catch(error => {
                    this.importing = false;
                    this.importResult = {
                        show: true,
                        success: false,
                        message: '系统错误：' + (error.message || '未知错误'),
                        details: null
                    };
                });
            }
        }
    });
</script>
</body>
</html> 